import cloud from '@lafjs/cloud'

let appid = ''
let secretKey = ''
let dbName = 'web-users'

export default async function (ctx: FunctionContext) {
  let { code, type } = ctx.body
  switch (type) {
    case "H5":
      appid = "wx267097d752f5c3fd"
      secretKey = "3fa70dc6ee45b4e90b2ab0fdc24dd778"
      break;

    default://pc
      appid = "wx2ae40a30ed25a63b"
      secretKey = "ae0e0a6eb4098623690f2f815f0f3c6f"
      break;
  }
  let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secretKey}&code=${code}&grant_type=authorization_code`
  const { data } = await cloud.fetch(url, {
    method: 'GET',
  });

  if (!data.openid) return cloud.utils.requestReturn({
    code: 500,
    msg: "授权失败"
  })


  let userInfo = await getUserInfo(data)

  let web = {
    nickname: userInfo.nickname,
    headimgurl: userInfo.headimgurl,
    sex: userInfo.sex,
    h5: {},
    pc: {}
  }
  if (type === "H5") {
    web.h5["openid"] = data.openid
    web["h5"]["unionid"] = data.unionid
  } else {
    web["pc"]["openid"] = data.openid
    web["pc"]["unionid"] = data.unionid
  }

  let whereJson = {}
  if (type === "H5") {
    whereJson = {
      h5: {
        openid: data.openid,
      }
    }
  } else {
    whereJson = {
      pc: {
        openid: data.openid,
      }
    }
  }

  let userId
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson,
  });

  let showMobile = false
  if (res && res._id) {
    userId = res._id
    if (res.mobile) {
      showMobile = false
    } else {
      showMobile = true
    }
  } else {
    showMobile = true
    userId = await addUser(web)
  }
  let token = cloud.utils.generateToken(userId)
  updateUserToken(token, userId)
  return cloud.utils.requestReturn({
    data: { showMobile, token }
  })
}
async function getUserInfo(params) {
  let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${params.access_token}&openid=${params.openid}`
  let { data } = await cloud.fetch(url, {
    method: 'GET',
  });
  return data
}

async function addUser(dataJson) {
  let res = await cloud.nw.db.add({
    dbName,
    dataJson,
    cancelAddTime: false
  });
  return res
}

//更新用户 token
async function updateUserToken(token: String, user_id: String) {
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: user_id, },
    dataJson: { token }
  });
}
